package com.mars.manager.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.mars.common.utils.CookieUtils;
import com.mars.common.utils.HttpClientUtil;
import com.mars.common.utils.WebUtil;
import com.mars.common.utils.date.DateUtil;
import com.mars.component.redis.JedisClient;
import com.mars.manager.constant.Const;
import com.mars.manager.user.entity.User;
import com.mars.web.common.pojo.ResponseResult;


/**
 * 登陆验证拦截器
 * @类名 LoginInterceptor
 * @日期 2016年12月25日 上午10:55:19
 * @作者 yhaoquan
 * @版权 (c) All Rights Reserved, 2016.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter{
	
	private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class) ;
	
	@Autowired
	private JedisClient jedisClient ;
	
	@Value("${SSO_BOSS_LOGIN_URL}")
	private String SSO_BOSS_LOGIN_URL ;
	
	/**
	 * SSO的Redis Session 的 KEY
	 */
	@Value("${SSO_REDIS_SESSION_KEY}")
	private String SSO_REDIS_SESSION_KEY ;
	
	/**
	 * Cookie中Token的KEY 
	 */
	@Value("${SSO_COOKIE_TOKEN}")
	private String SSO_COOKIE_TOKEN ;
	
	/**
	 * 根据Token获取Redis Session中的用户
	 */
	@Value("${SSO_BOSS_GET_REDIS_SESSION_USER_URL}")
	private String SSO_BOSS_GET_REDIS_SESSION_USER_URL ;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		String currentUrl = WebUtil.getCurrentUrl(request) ;
		
		String token = CookieUtils.getCookieValue(request, SSO_COOKIE_TOKEN) ;
		
		if(null == token) { //Token不存在，跳转到登陆页面
			logger.info("用户未登陆，跳转到登陆页面【用户IP:{},访问时间:{},访问页面:{}】", WebUtil.getIpAddress(request), DateUtil.getCurrentDateTimeString(), currentUrl);
			response.sendRedirect(SSO_BOSS_LOGIN_URL+"?redirectURL="+WebUtil.encodeURL(currentUrl));
			return false ;
		} else {
			//根据Cookie上的Token去查找缓存中是否存在该Token
			String userJson = HttpClientUtil.doGet(SSO_BOSS_GET_REDIS_SESSION_USER_URL+token) ;
			
			ResponseResult result = JSON.parseObject(userJson, ResponseResult.class) ;
			
			if(result.getStatus()) {
				User user = JSON.parseObject(result.getData().toString(), User.class);
				//保存当前用户信息在局部Session中
				WebUtil.setSessionAttribute(request, Const.CurrentUser, user);
			} else {
				logger.info("用户登陆超时，跳转到登陆页面【用户IP:{},访问时间:{},访问页面:{}】", WebUtil.getIpAddress(request), DateUtil.getCurrentDateTimeString(), currentUrl);
				response.sendRedirect(SSO_BOSS_LOGIN_URL+"?redirectURL="+WebUtil.encodeURL(currentUrl));
				return false ;
			}
		}
		
		return super.preHandle(request, response, handler);
	}
	
}
